//
//  ViewController.m
//  七牛demo
//
//  Created by Fei Cao on 15/9/23.
//  Copyright © 2015年 caofei. All rights reserved.
//

#import "ViewController.h"
#import <QiniuSDK.h>
//#import <AssetsLibrary/AssetsLibrary.h>
//#import <Photos/Photos.h>

#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "DNImagePickerController.h"
#import "DNAsset.h"



#import "MLSelectPhotoPickerViewController.h"
#import "MLSelectPhotoAssets.h"
@interface ViewController ()<DNImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *MLSelectPhotoBtn;
@property (weak, nonatomic) IBOutlet UIImageView *headImage;
@property (weak, nonatomic) IBOutlet UIButton *upBtn;
@property (weak, nonatomic) IBOutlet UIButton *MLVideoBtn;
@property (nonatomic, strong) NSMutableArray *assetsArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.assetsArray = [NSMutableArray array];
    
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:@"http://7xlxn2.com1.z0.glb.clouddn.com/2015-09-24_22:57:30_aZH7y4Sq.png?&e=1443433730&token=weS42ixfmN2hO6-9Io8T9y3A_yLonirJ83luY3V4:ZV0JeXbnoUsQTtx_AjmpwXzpBfU="] placeholderImage:nil];
    
    //    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    [manager.requestSerializer setTimeoutInterval:10.f];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //
    //    [manager POST:@"http://localhost/info.php" parameters:nil
    //          success:^(AFHTTPRequestOperation *operation,id responseObject) {
    //
    //              NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableLeaves error:nil];
    //              [self.headImage sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:nil];
    //
    //          }failure:^(AFHTTPRequestOperation *operation,NSError *error) {
    //
    //          }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)upLoad:(NSData*)_data andKey:(NSString *)_key{
    
    // Your Token Here, See: http://developer.qiniu.com/docs/v6/api/reference/security/upload-token.html
    NSString *token = @"weS42ixfmN2hO6-9Io8T9y3A_yLonirJ83luY3V4:9NB1yXrXzSYfl_7xyinAif_DFIY=:eyJzY29wZSI6InRlc3QiLCJkZWFkbGluZSI6MTQ0NDMxOTYzN30=";
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
   
  
    
    // ------------------- Test putData -------------------------
    //            NSData *data = [@"Hello, W(NSString *key, float percent)orld!" dataUsingEncoding : NSUTF8StringEncoding];
    [upManager putData:_data key:_key token:token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                  NSLog(@"%@", info);
                  NSLog(@"%@", resp);
              } option:nil];
    
    // ------------------- Test putFile -------------------------
    //        NSString *path = [[NSBundle mainBundle] pathForResource:@"the_v" ofType:@"png"];
    //
    //        NSString *fileName = [NSString stringWithFormat:@"%@_%@.png", [self getDateTimeString], [self randomStringWithLength:8]];
    //
    //        [upManager putFile:path
    //                       key:fileName
    //                     token:token
    //                  complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
    //
    //                      NSLog(@" --->> Info: %@  ", info);
    //                      NSLog(@" ---------------------");
    //                      NSLog(@" --->> Response: %@,  ", resp);
    //
    //                  } option:nil];
    
    
}
-(IBAction)MLAction:(id)sender{
    // 创建控制器
    MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
    // 默认显示相册里面的内容SavePhotos
    pickerVc.status = PickerViewShowStatusCameraRoll;
    pickerVc.maxCount = 9;
    [pickerVc showPickerVc:self];
    __weak typeof(self) weakSelf = self;
    pickerVc.callBack = ^(NSArray *assets){
        [weakSelf.assetsArray removeAllObjects];
        for (MLSelectPhotoAssets *asset in assets) {
            [weakSelf.assetsArray addObject:[MLSelectPhotoPickerViewController getImageWithImageObj:asset]];
            //            上传图片
            NSData * data = UIImagePNGRepresentation([MLSelectPhotoPickerViewController getImageWithImageObj:asset]);
            NSString * uuid=[[NSUUID UUID] UUIDString];
            [weakSelf upLoad:data andKey:uuid];

        }

    };


}

-(IBAction)MLVideoAction:(id)sender{
    // 创建控制器
    MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
    // 默认显示相册里面的视频
    // 最多能选1个视频
    pickerVc.maxCount = 1;
    pickerVc.status = PickerViewShowStatusVideo;
    [pickerVc showPickerVc:self];
   
     //传值可以用代理，或者用block来接收，以下是block的传值
     __weak typeof(self) weakSelf = self;
     pickerVc.callBack = ^(NSArray *assets){
         for (MLSelectPhotoAssets *asset in assets) {
                if ([asset isKindOfClass:[MLSelectPhotoAssets class]]){{
                 [weakSelf.assetsArray addObject:asset.asset.defaultRepresentation.url];
                }
             }
         };
     };
}

- (IBAction)buttonAction:(id)sender
{
    DNImagePickerController *imagePicker = [[DNImagePickerController alloc] init];
    imagePicker.imagePickerDelegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

//-(void)readlib:(DNAsset *)_dnasset{
//    ALAssetsLibrary *lib = [ALAssetsLibrary new];
//    __weak typeof(self) weakSelf = self;
//    [lib assetForURL:_dnasset.url resultBlock:^(ALAsset *asset) {
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        if (asset) {
//            //            导出图片
//            UIImage * image = [strongSelf readImage:asset];
////            上传图片
//            NSData * data = UIImagePNGRepresentation(image);
//            NSString * uuid=[[NSUUID UUID] UUIDString];
//             [strongSelf upLoad:data andKey:uuid];
//        }else{
//            // On iOS 8.1 [library assetForUrl] Photo Streams always returns nil. Try to obtain it in an alternative way
//            [lib enumerateGroupsWithTypes:ALAssetsGroupPhotoStream
//                               usingBlock:^(ALAssetsGroup *group, BOOL *stop)
//             {
//                 [group enumerateAssetsWithOptions:NSEnumerationReverse
//                                        usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
//                                            
//                                            if([[result valueForProperty:ALAssetPropertyAssetURL] isEqual:_dnasset.url])
//                                            {
//                                                //            导出图片
//                                                UIImage * image = [strongSelf readImage:asset];
//                                                //            上传图片
//                                                NSData * data = UIImagePNGRepresentation(image);
//                                                NSString * uuid=[[NSUUID UUID] UUIDString];
//                                                [strongSelf upLoad:data andKey:uuid];
//                                                *stop = YES;
//                                            }
//                                        }];
//             }
//                             failureBlock:^(NSError *error)
//             {
//                 //                 导出图片
//                 [strongSelf readImage:nil];
//             }];
//        }
//    } failureBlock:^(NSError *error) {
//        
//    }];
//    
//}


//-(UIImage *)readImage:(ALAsset *)asset{
//    if (!asset) {
//        return nil;
//    }
//    
//    NSNumber *orientationValue = [asset valueForProperty:ALAssetPropertyOrientation];
//    UIImageOrientation orientation = UIImageOrientationUp;
//    if (orientationValue != nil) {
//        orientation = [orientationValue intValue];
//    }
//    
//    UIImage * image = [UIImage imageWithCGImage:asset.thumbnail];
//    //    image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
//    return image;
//}

#pragma mark - Load Assets

//- (void)loadAssets {
//    if (NSClassFromString(@"PHAsset")) {
//        
//        // Check library permissions
//        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
//        if (status == PHAuthorizationStatusNotDetermined) {
//            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
//                if (status == PHAuthorizationStatusAuthorized) {
//                    [self performLoadAssets];
//                }
//            }];
//        } else if (status == PHAuthorizationStatusAuthorized) {
//            [self performLoadAssets];
//        }
//        
//    } else {
//        
//        // Assets library
//        [self performLoadAssets];
//        
//    }
//}

//- (void)performLoadAssets {
//    
//    // Initialise
////    _assets = [NSMutableArray new];
//    
//    // Load
//    if (NSClassFromString(@"PHAsset")) {
//        
//        // Photos library iOS >= 8
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            PHFetchOptions *options = [PHFetchOptions new];
//            options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
//            PHFetchResult *fetchResults = [PHAsset fetchAssetsWithOptions:options];
//            [fetchResults enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
////                [_assets addObject:obj];
//            }];
//            if (fetchResults.count > 0) {
////                [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
//            }
//        });
//        
//    } else {
//        
//        // Assets Library iOS < 8
//        _ALAssetsLibrary = [[ALAssetsLibrary alloc] init];
//        
//        // Run in the background as it takes a while to get all assets from the library
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            
//            NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
//            NSMutableArray *assetURLDictionaries = [[NSMutableArray alloc] init];
//            
//            // Process assets
//            void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
//                if (result != nil) {
//                    NSString *assetType = [result valueForProperty:ALAssetPropertyType];
//                    if ([assetType isEqualToString:ALAssetTypePhoto] || [assetType isEqualToString:ALAssetTypeVideo]) {
//                        [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
//                        NSURL *url = result.defaultRepresentation.url;
//                        [_ALAssetsLibrary assetForURL:url
//                                          resultBlock:^(ALAsset *asset) {
//                                              if (asset) {
//                                                  @synchronized(_assets) {
//                                                      [_assets addObject:asset];
//                                                      if (_assets.count == 1) {
//                                                          // Added first asset so reload data
//                                                          [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
//                                                      }
//                                                  }
//                                              }
//                                          }
//                                         failureBlock:^(NSError *error){
//                                             NSLog(@"operation was not successfull!");
//                                         }];
//                        
//                    }
//                }
//            };
//            
//            // Process groups
//            void (^ assetGroupEnumerator) (ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
//                if (group != nil) {
//                    [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:assetEnumerator];
//                    [assetGroups addObject:group];
//                }
//            };
//            
//            // Process!
//            [_ALAssetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
//                                            usingBlock:assetGroupEnumerator
//                                          failureBlock:^(NSError *error) {
//                                              NSLog(@"There is an error");
//                                          }];
//            
//        });
//        
//    }
//    
//}


#pragma mark - DNImagePickerControllerDelegate

- (void)dnImagePickerController:(DNImagePickerController *)imagePickerController sendImages:(NSArray *)imageAssets isFullImage:(BOOL)fullImage
{
    self.assetsArray = [NSMutableArray arrayWithArray:imageAssets];
    for (DNAsset * dnasset in self.assetsArray) {
//        [self readlib:dnasset];
    }
}

- (void)dnImagePickerControllerDidCancel:(DNImagePickerController *)imagePicker
{
    [imagePicker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - Helpers

- (NSString *)getDateTimeString
{
    NSDateFormatter *formatter;
    NSString        *dateString;
    
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    
    dateString = [formatter stringFromDate:[NSDate date]];
    
    return dateString;
}


- (NSString *)randomStringWithLength:(int)len
{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (int i=0; i<len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((int)[letters length])]];
    }
    
    return randomString;
}
@end
